package pl.prv.polanie.client.filemanager;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.HTTPRequest;
import com.google.gwt.user.client.ResponseTextHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.SimplePanel;



public class FileManagerController extends SimplePanel {
	
	Directory dir = new Directory();
	
	
	public FileManagerController() {
		
		setWidget(dir);
		
		
		ResponseTextHandler rth = new ResponseTextHandler() {
			public void onCompletion(String responseText) {
//				Window.alert("A " +  responseText);
//				dir.setDirName("mars.iti.pk.edu.pl/~swoosh/");
//				dir.setPath("http://mars.iti.pk.edu.pl/~swoosh/");

//				dir.setDirName("dirName");
//				dir.setPath("path");
				
				dir.setDirName("Files");
				dir.setPath("http://localhost/gwt/");
				
				try {
					JSONValue val = JSONParser.parse(responseText);
					parseOneLevel(val, dir);
				} catch (NullPointerException e) {
					Window.alert("NPE " + e.toString() );
				} catch (Exception e) {
					Window.alert("EXC " + e.toString());
				}
				dir.setCollapsedRecursively(false);
			}
		};
		
		HTTPRequest.asyncGet("dane2.php", rth);
//		HTTPRequest.asyncGet("http://localhost/gwt/dane2.php", rth);
	}
	
	
	
	private void parseOneLevel(final JSONValue jsonVal, final Directory parentDir) {
		try {
			JSONArray arr = jsonVal.isArray();
			
			for (int i = 0; i < arr.size(); i++) {
				JSONValue v = arr.get(i);
				JSONObject obj = v.isObject();
				
				JSONValue vName = obj.get("name");
				JSONString name = vName.isString();
				
				JSONValue vContent = obj.get("content");
				
				//katalog
				// && (vContent.isNull() == null)  z tym katalogi byly biale te zagn
				if (vContent != null ) {
					final Directory d = new Directory();
					d.setDirName(name.stringValue());
					d.setPath(parentDir.getPath() + name.stringValue());
					parentDir.addChild(d);
					
					if (vContent.isNull() == null) {
						parseOneLevel(vContent, d);	
					}
					
				}
				//plik
				else {
					final File f = new File(parentDir.getPath(), name.stringValue());
					parentDir.addChild(f);
				}
			}
			
		} catch (NullPointerException e) {
			Window.alert("NullPointerException " + e.toString() );
		} catch (Exception e) {
			Window.alert("Exception " + e.toString());
		}
	}



	public Directory getDir() {
		return dir;
	}

}
